package com.chang.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/*
 * @Author Changzhenxi
 * @Date 2024/1/15 9:44
 * @Description 只要将CorsWebFilter注入容器就可以解决跨域问题
 * @Since version 1.0
 */
@Configuration
public class GuliMallCorsConfig {
    @Bean
    public CorsWebFilter corsWebFilter(){
        // new CorsWebFilter()需要传入配置信息,而UrlBasedCorsConfigurationSource实现了配置接口,所以直接new
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1,配置跨域条件
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOriginPattern("*");  // 允许哪些请求来源进行跨域
        corsConfiguration.setAllowCredentials(true); // 是否允许携带cookie进行跨域

        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}
